package com.coderli.onecoder.agent.common;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ClassResolvers;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 和Hypervisor Server通信的客户端
 * 
 * @author lihzh
 * @date 2012-6-29 下午2:45:42
 */
public class AgentClient {

	private static final Logger log = LoggerFactory.getLogger(AgentClient.class);
	private String serverIp;
	private int port;

	public AgentClient(String ip, int port) {
		this.serverIp = ip;
		this.port = port;
		AgentConfig.getConfig();
	}

	/**
	 * 通过NIO跟服务端绑定
	 * 
	 * @author lihzh
	 * @date 2012-6-29 下午2:47:12
	 */
	public void bindToServer() {
		// 配置NIO客户端启动
		ClientBootstrap bootstrap = new ClientBootstrap(
				new NioClientSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(
						new ObjectEncoder(), 
						new ObjectDecoder(ClassResolvers
								.cacheDisabled(getClass().getClassLoader())),
						new AgentCommandHandler());
			}
		});
		if (log.isDebugEnabled()) {
		}
		bootstrap.connect(new InetSocketAddress(serverIp, port));
	}

}
